/**
 * Created by bian on 16-3-11.
 */
require('../admin-base/common.js');
require('fex-webuploader/dist/webuploader.css');
require('../../css/lib/webuploader.scss');
require('../../css/img-upload-thumbnail.scss');

/* js */
var $ = jQuery;
var WebUploader = require('fex-webuploader');


require('angular');


$(function() {
    var app = angular.module('app', []);

    var uploader = new WebUploader.Uploader({
        swf: '/dist/Uploader.swf',
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        },
        pick: {
            id: '#upload-picker',
            multiple: true
        },
        fileSizeLimit: 1024 * 1024 * 3,
        fileNumLimit: 10,
        server: '/upload'
    });

    var uploaded = false;
    var $form = $('form');

    app.controller('formCtrl',['$scope','$http',function(scope,$http){
        scope.imgs = [];
        scope.imgsUrl = [];
        scope.data = [];

        scope.remove = function (index) {
            scope.data.splice(index, 1);
            scope.imgs.splice(index, 1);
        };

        scope.init = function () {
            var imgDom = angular.element('#imgs');
            try {
                scope.data = JSON.parse(imgDom.html());
            } catch (e){
                console.log(e);
                scope.data = [];
            }

            scope.imgs = scope.data.slice();
        };

        scope.init();

        uploader.on('fileQueued', function (file) {
            uploader.makeThumb( file, function( error, ret ) {
                if ( error ) {
                    alert('预览失败，请刷新重试');
                } else {
                    scope.imgs.push(ret);
                    scope.data.push(file);
                    scope.$apply();
                }
            }, 640, 260);
        });

        uploader.on('uploadSuccess', function (file, ret) {
            for(var i in scope.data) {
                var ele = scope.data[i];
                //debugger
                if (ele.id && ele.id == file.id) {
                    scope.data[i] =  ret.file_path;
                    break;
                }
            }
        });

        uploader.on('uploadFinished', function () {
            for(var i in scope.data) {
                var filePath = scope.data[i];
                scope.imgsUrl.push(filePath);
            }
            //scope.mainImgUrl = scope.imgsUrl[scope.mainImg];
            scope.$apply();
            $form[0].submit();
        });

        $form.submit(function(event){
            if (uploaded) {
               // form.submit();
                return;
            }else{
                uploaded = true;
                uploader.upload();
                event.preventDefault();
            }
        });
    }]);

    angular.bootstrap(document.documentElement, ['app']);
});